package com.dynamic;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Selection;
import android.text.Spannable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import br.com.pierry.simpletoast.SimpleToast;

import com.dxyxx.R;
import com.dxyxx.dialog.AgainPlayer;
import com.dxyxx.dialog.DKDialog;
import com.dxyxx.framework.BaseActivity;
import com.dxyxx.framework.CAS;
import com.dxyxx.framework.InfoActivity;
import com.dxyxx.framework.CAS.CallBack;
import com.dxyxx.framework.ResultCode;
import com.dxyxx.pojo.ZimgResult;
import com.gghl.view.wheelview.ActionSheetDialog;
import com.gghl.view.wheelview.ActionSheetDialog.OnSheetItemClickListener;
import com.gghl.view.wheelview.ActionSheetDialog.SheetItemColor;
import com.http.HttpUtil;
import com.http.ImageHttpUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

/**
 * 编写 评论。 上传图片然后调用info接口得到图片的高度跟宽度。
 * 
 * @author Administrator
 * 
 */
public class WriteActivity extends BaseActivity implements OnItemClickListener {

	private GridView gridview;
	private GridAdapter adapter;
	private String pid;
	private ImageView activity_selectimg_send;
	private EditText comment_content;
//	private LinearLayout selectimg_relativeLayout_below;
	private ScrollView activity_selectimg_scrollView;
	private HorizontalScrollView selectimg_horizontalScrollView;
	private Context context;
	private float dp;

	List<String> urList = new ArrayList<String>();
	public List<Bitmap> bmp = new ArrayList<Bitmap>();
	public List<String> drr = new ArrayList<String>();

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_selectimg);
		context = this;
		initViews();
	}

	private BitmapFactory.Options opts;
	private DKDialog dialog;

	public void initViews() {
		Bundle bundle = this.getIntent().getExtras();
		if (bundle != null) {// 带有product
			pid = bundle.getString("productId");
		}// 初始化opt
		opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = true;
		opts.inSampleSize = 1;
		//		opts.inJustDecodeBounds = false;
		opts.inJustDecodeBounds = true;
		//只有这样才能得到最原始的长度高度
		sb = new StringBuilder();
		dp = getResources().getDimension(R.dimen.dp);// 10dp
		comment_content = (EditText) findViewById(R.id.comment_content);
		comment_content.setFocusable(true);
		comment_content.setFocusableInTouchMode(true);

		ImageView back = (ImageView) findViewById(R.id.backImageButton);
		back.setImageResource(R.drawable.common_cancel_switcher);//替换样式
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				WriteActivity.this.finish();
			}
		});

		((TextView) findViewById(R.id.title)).setText("快来吐槽");// 标题
		selectimg_horizontalScrollView = (HorizontalScrollView) findViewById(R.id.selectimg_horizontalScrollView);
		gridview = (GridView) findViewById(R.id.noScrollgridview);
		gridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
		gridviewInit();

		activity_selectimg_send = (ImageView) findViewById(R.id.nextImageButton);
		activity_selectimg_send.setImageResource(R.drawable.common_accept_switcher);
		activity_selectimg_send.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// 开始旋转等待。 

				if (bmp.size() < 1) {
					SimpleToast.info(context, "至少需要一张图片");
					//Toast.makeText(getApplicationContext(),, Toast.LENGTH_SHORT).show();
					return;
				}

				((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(WriteActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

				String content = comment_content.getText().toString().trim();
				if (content.equals("")) {
					SimpleToast.info(context, "发布的内容不能为空");
					return;
				}
				for (int i = 0; i < drr.size(); i++) {
					urList.add(drr.get(i));
				}
				//activity_selectimg_send.setEnabled(false);

				// 图片地址 urList；
				allDone = new boolean[urList.size()];
				for (int i = 0; i < urList.size(); i++) {
					//String[] strs = urList.get(i).split("\\.");// 得到contentType
					//					RequestParams params = new RequestParams();
					//					byte[] myByteArray = getBytesFromFile(new File(urList.get(i)));// 得到二进制流
					//					params.put("file", new ByteArrayInputStream(myByteArray), "file");
					try {
						File myFile = new File(urList.get(i));
						RequestParams params = new RequestParams();
						params.put("userfile", myFile);
						dialog = new DKDialog(WriteActivity.this, R.style.MyDialog);
						dialog.setContentView(R.layout.common_alertdialog);
						ImageHttpUtil.rawpost(params, new ImageHandler(i));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});

//		selectimg_relativeLayout_below = (LinearLayout) findViewById(R.id.selectimg_relativeLayout_below);
		activity_selectimg_scrollView = (ScrollView) findViewById(R.id.activity_selectimg_scrollView);
		activity_selectimg_scrollView.setVerticalScrollBarEnabled(false);

		final View decorView = getWindow().getDecorView();
		final WindowManager wm = this.getWindowManager();

		decorView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			@Override
			public void onGlobalLayout() {
				@SuppressWarnings("deprecation")
				int displayheight = wm.getDefaultDisplay().getHeight();
				Rect rect = new Rect();
				decorView.getWindowVisibleDisplayFrame(rect);
				int dynamicHight = rect.bottom - rect.top;
				float ratio = (float) dynamicHight / (float) displayheight;

				if (ratio > 0.2f && ratio < 0.6f) {
//					selectimg_relativeLayout_below.setVisibility(View.VISIBLE);
					activity_selectimg_scrollView.scrollBy(0, activity_selectimg_scrollView.getHeight());
				} else {
					//selectimg_relativeLayout_below.setVisibility(View.GONE);
				}
			}
		});

	}

	private StringBuilder sb;

	//处理图片上传机制
	class ImageHandler extends AsyncHttpResponseHandler {
		private int num;

		public ImageHandler(int num) {
			this.num = num;
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
			Toast.makeText(WriteActivity.this, "有点问题", 1).show();
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			try {
				// get image的 width跟height
				File file = new File(urList.get(num));
				if (file.exists()) {

					// 下面这句话 会导致oom
					/**
					 * opts.inJustDecodeBounds = true; 搭配 Bitmap bm =
					 * BitmapFactory.decodeFile(urList.get(num), opts); 然后
					 * bm.getWidth() 会造成oom
					 */
					Bitmap bm = BitmapFactory.decodeFile(urList.get(num), opts);
					int w = opts.outWidth;
					int h = opts.outWidth;

					ZimgResult zr = getObjectMapper().readValue(arg2, ZimgResult.class);
					if (!zr.getMd5().equals("false")) {
						sb.append(zr.getMd5() + "_" + w + "_" + h + ";");
					}
				}
				//   "product_id":null,"images":"d19454143c10a1010d61b2fc449895c2_480_480c2fd49e51cfc5ae0b549519a09f6ec0c_480_480","user_id":"15201967267","postTime":1428821342217,"id":2}}

				//sb.deleteCharAt(sb.length() - 1);//去除最后一个字符
				// 全部结束了，上传
				if (allFinish(num)) {
					// 这段要加 CAS 判断
					CAS call = new CAS(WriteActivity.this, Write, new CallBack() {
						@Override
						public void method() {
							postComment();
						}
					});
					call.call();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

	private void postComment() {

		String url = "comment/add";
		RequestParams params = new RequestParams();
		params.add("word", comment_content.getText().toString());
		params.add("images", sb.deleteCharAt(sb.length() - 1).toString());//去掉最后一个分号
		if (pid != null) {
			params.add("product_id", pid);
		}
		HttpUtil.post(url, params, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				AgainPlayer againPlayer = new AgainPlayer(WriteActivity.this, new com.dxyxx.dialog.AgainPlayer.CallBack() {
					@Override
					public void method() {
						postComment();
					}
				});
				againPlayer.call("貌似没网了！");
				dialog.dismiss();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				System.out.println(new String(arg2));
				SimpleToast.ok(context, "吐槽成功");
				Intent intent = new Intent();
				// 关闭Activity
				intent.putExtra("result", "发布成功");
				// 设置返回数据
				WriteActivity.this.setResult(ResultCode.CommentSuccess, intent);
				WriteActivity.this.finish();
				dialog.dismiss();
			}

		});
	}

	private boolean[] allDone;

	// 判断是不是所有 子进程都结束了
	public boolean allFinish(int num) {
		synchronized (allDone) {
			//一次只能有一个线程进入
			allDone[num] = true;
			for (boolean tmp : allDone) {
				if (!tmp) {
					return false;
				}
			}
			return true;
		}
	}

	public byte[] getBytesFromFile(File f) {
		if (f == null) {
			return null;
		}
		try {
			FileInputStream stream = new FileInputStream(f);
			ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
			byte[] b = new byte[1000];
			int n;
			while ((n = stream.read(b)) != -1)
				out.write(b, 0, n);
			stream.close();
			out.close();
			return out.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void gridviewInit() {
		adapter = new GridAdapter(this);
		adapter.setSelectedPosition(0);
		int size = 0;
		if (bmp.size() < 6) {
			size = bmp.size() + 1;
		} else {
			size = bmp.size();
		}
		LayoutParams params = gridview.getLayoutParams();
		final int width = size * (int) (dp * 9.4f);
		params.width = width;
		gridview.setLayoutParams(params);
		gridview.setColumnWidth((int) (dp * 9.4f));
		gridview.setStretchMode(GridView.NO_STRETCH);
		gridview.setNumColumns(size);
		gridview.setAdapter(adapter);
		gridview.setOnItemClickListener(this);

		selectimg_horizontalScrollView.getViewTreeObserver().addOnPreDrawListener(// 绘制完毕
				new OnPreDrawListener() {
					public boolean onPreDraw() {
						selectimg_horizontalScrollView.scrollTo(width, 0);
						selectimg_horizontalScrollView.getViewTreeObserver().removeOnPreDrawListener(this);
						return false;
					}
				});
	}

	protected void onPause() {
		// temp=comment_content.getText().toString().trim();
		super.onPause();
	}

	public class GridAdapter extends BaseAdapter {
		private LayoutInflater listContainer;
		private int selectedPosition = -1;
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public class ViewHolder {
			public ImageView image;
			public Button bt;
		}

		public GridAdapter(Context context) {
			listContainer = LayoutInflater.from(context);
		}

		public int getCount() {
			if (bmp.size() < 6) {
				return bmp.size() + 1;
			} else {
				return bmp.size();
			}
		}

		public Object getItem(int arg0) {

			return null;
		}

		public long getItemId(int arg0) {

			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		/**
		 * ListView Item设置
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			final int sign = position;
			// 自定义视图
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				// 获取list_item布局文件的视图

				convertView = listContainer.inflate(R.layout.item_published_grida, null);

				// 获取控件对象
				holder.image = (ImageView) convertView.findViewById(R.id.item_grida_image);
				holder.bt = (Button) convertView.findViewById(R.id.item_grida_bt);
				// 设置控件集到convertView
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (position == bmp.size()) {
				holder.image.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_addpic_unfocused));
				holder.bt.setVisibility(View.GONE);
				if (position == 6) {
					holder.image.setVisibility(View.GONE);
				}
			} else {
				holder.image.setImageBitmap(bmp.get(position));
				holder.bt.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						PhotoActivity.bitmap.remove(sign);
						bmp.get(sign).recycle();
						bmp.remove(sign);
						drr.remove(sign);

						gridviewInit();
					}
				});
			}

			return convertView;
		}
	}

	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, View parent) {

			View view = View.inflate(mContext, R.layout.item_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
			// ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
			// R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);
			update();

			Button bt1 = (Button) view.findViewById(R.id.item_popupwindows_camera);
			Button bt2 = (Button) view.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view.findViewById(R.id.item_popupwindows_cancel);
			bt1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					photo();
					dismiss();
				}
			});
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Intent i = new Intent(
					// 相册
							Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					startActivityForResult(i, RESULT_LOAD_IMAGE);
					dismiss();
				}
			});
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});

		}
	}

	private static final int TAKE_PICTURE = 0;
	private static final int RESULT_LOAD_IMAGE = 1;
	private static final int CUT_PHOTO_REQUEST_CODE = 2;
	private static final int SELECTIMG_SEARCH = 3;
	private static final int Write = 4;
	private String path = "";
	private Uri photoUri;
	private File file = null;

	public void photo() {
		try {
			Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

			String sdcardState = Environment.getExternalStorageState();
			String sdcardPathDir = android.os.Environment.getExternalStorageDirectory().getPath() + "/tempImage/";

			if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
				// 有sd卡，是否有myImage文件夹
				File fileDir = new File(sdcardPathDir);
				if (!fileDir.exists()) {
					fileDir.mkdirs();
				}
				// 是否有headImg文件
				file = new File(sdcardPathDir + System.currentTimeMillis() + ".JPEG");
			}
			if (file != null) {
				path = file.getPath();
				photoUri = Uri.fromFile(file);
				openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);

				startActivityForResult(openCameraIntent, TAKE_PICTURE);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case TAKE_PICTURE:
			if (drr.size() < 6 && resultCode == -1) {// 拍照

				if (file.length() < (500 * 1000)) {
					startPhotoZoom(file.getAbsolutePath());
				} else {
					// 大于500kb ，裁剪
					startPhotoZoom(photoUri, true);
				}

			}
			break;
		case RESULT_LOAD_IMAGE:
			if (drr.size() < 6 && resultCode == RESULT_OK && null != data) {// 相册返回
				Uri uri = data.getData();
				if (uri != null) {
					File file = new File(getRealPathFromURI(uri));

					if (file.length() < (500 * 1000)) {
						startPhotoZoom(uri);
					} else {
						// 大于500kb ，裁剪
						startPhotoZoom(uri, true);
					}
				}
			}

			break;
		case CUT_PHOTO_REQUEST_CODE:
			if (resultCode == RESULT_OK && null != data) {// 裁剪返回
				Bitmap bitmap = Bimp.getLoacalBitmap(drr.get(drr.size() - 1));
				PhotoActivity.bitmap.add(bitmap);
				bitmap = Bimp.createFramedPhoto(480, 480, bitmap, (int) (dp * 1.6f));
				bmp.add(bitmap);
				gridviewInit();
			}
			break;
		case SELECTIMG_SEARCH:
			if (resultCode == RESULT_OK && null != data) {
				String text = "#" + data.getStringExtra("topic") + "#";
				text = comment_content.getText().toString() + text;
				comment_content.setText(text);

				comment_content.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
					public boolean onPreDraw() {
						comment_content.setEnabled(true);
						// 设置光标为末尾
						CharSequence cs = comment_content.getText();
						if (cs instanceof Spannable) {
							Spannable spanText = (Spannable) cs;
							Selection.setSelection(spanText, cs.length());
						}
						comment_content.getViewTreeObserver().removeOnPreDrawListener(this);
						return false;
					}
				});

			}

			break;
		case Write: //写评论
			postComment();
			break;
		}
	}

	//见http://www.tuicool.com/articles/Nj2eam
	public String getRealPathFromURI(Uri contentUri) {
		String res = null;
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
		if (cursor.moveToFirst()) {
			;
			int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			res = cursor.getString(column_index);
		}
		cursor.close();
		return res;
	}

	private void startPhotoZoom(Uri uri) {
		//		try {
		// 获取系统时间 然后将裁剪后的图片保存至指定的文件夹
		//SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
		//String address = sDateFormat.format(new java.util.Date());
		//if (!FileUtils.isFileExist("")) {
		//	FileUtils.createSDDir("");

		//}
		//			drr.add(FileUtils.SDPATH + address + ".JPEG");
		drr.add(getRealPathFromURI(uri));
		//Uri imageUri = Uri.parse("file:///sdcard/formats/" + address + ".JPEG");

		//final Intent intent = new Intent("com.android.camera.action.CROP");

		//intent.setDataAndType(uri, "image/*");

		//intent.putExtra("crop", "true");
		//intent.putExtra("aspectX", 1);
		//intent.putExtra("aspectY", 1);
		//intent.putExtra("outputX", 480);
		//intent.putExtra("outputY", 480);
		// 输出路径
		//intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		// 输出格式
		//intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		// 不启用人脸识别
		//intent.putExtra("noFaceDetection", false);
		//intent.putExtra("return-data", false);
		//startActivityForResult(intent, CUT_PHOTO_REQUEST_CODE);

		//		} catch (IOException e) {
		//			e.printStackTrace();
		//		}
		Bitmap bitmap = Bimp.getLoacalBitmap(drr.get(drr.size() - 1));
		PhotoActivity.bitmap.add(bitmap);
		bitmap = Bimp.createFramedPhoto(480, 480, bitmap, (int) (dp * 1.6f));
		bmp.add(bitmap);
		gridviewInit();
	}

	private void startPhotoZoom(Uri uri, boolean cut) {
		try {
			//获取系统时间 然后将裁剪后的图片保存至指定的文件夹
			SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
			String address = sDateFormat.format(new java.util.Date());
			if (!FileUtils.isFileExist("")) {
				FileUtils.createSDDir("");
			}
			drr.add(FileUtils.SDPATH + address + ".JPEG");
			Uri imageUri = Uri.parse("file:///sdcard/formats/" + address + ".JPEG");

			final Intent intent = new Intent("com.android.camera.action.CROP");

			intent.setDataAndType(uri, "image/*");

			intent.putExtra("crop", "true");
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("outputX", 480);
			intent.putExtra("outputY", 480);
			// 输出路径
			intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
			// 输出格式
			intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
			// 不启用人脸识别
			intent.putExtra("noFaceDetection", false);
			intent.putExtra("return-data", false);
			startActivityForResult(intent, CUT_PHOTO_REQUEST_CODE);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void startPhotoZoom(String file) {

		drr.add(file);

		Bitmap bitmap = Bimp.getLoacalBitmap(drr.get(drr.size() - 1));
		PhotoActivity.bitmap.add(bitmap);
		bitmap = Bimp.createFramedPhoto(480, 480, bitmap, (int) (dp * 1.6f));
		bmp.add(bitmap);
		gridviewInit();
	}

	protected void onDestroy() {

		FileUtils.deleteDir(FileUtils.SDPATH);
		FileUtils.deleteDir(FileUtils.SDPATH1);
		// 清理图片缓存
		for (int i = 0; i < bmp.size(); i++) {
			bmp.get(i).recycle();
		}
		for (int i = 0; i < PhotoActivity.bitmap.size(); i++) {
			PhotoActivity.bitmap.get(i).recycle();
		}
		PhotoActivity.bitmap.clear();
		bmp.clear();
		drr.clear();
		super.onDestroy();
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(WriteActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		if (arg2 == bmp.size()) {
			String sdcardState = Environment.getExternalStorageState();
			if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
				//				new PopupWindows(WriteActivity.this, gridview);

				// 
				new ActionSheetDialog(WriteActivity.this).builder().setCancelable(true).setCanceledOnTouchOutside(true).addSheetItem("拍照", SheetItemColor.Blue, new OnSheetItemClickListener() {
					@Override
					public void onClick(int which) {
						photo();

					}
				}).addSheetItem("从相册中选取", SheetItemColor.Blue, new OnSheetItemClickListener() {
					@Override
					public void onClick(int which) {

						Intent i = new Intent(
						// 相册
								Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
						startActivityForResult(i, RESULT_LOAD_IMAGE);
					}
				}).show();

			} else {
				SimpleToast.error(context, "sdcard已拔出，不能选择照片");
			}
		} else {
			Intent intent = new Intent(WriteActivity.this, PhotoActivity.class);

			intent.putExtra("ID", arg2);
			startActivity(intent);
		}
	}

}
